//
//  JiaoZiTaxiApp.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/8/23.
//

import ComposableArchitecture
import os
import SwiftUI
import QYSDK
import UserNotifications
import Localize_Swift

let logger = LoggerHelper.shared

class AppDelegate: NSObject, UIApplicationDelegate {
   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
      logger.info("appliaction launching...")
      registerForPushNotifications()

      // 网易七鱼集成
      QYSDK.shared().registerAppId("fc191a11af9e7393abb78568ae6c1bc6", appName: "JiaoZiTaxi")

      return true
   }

   func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
      logger.info("register remote notification with device token...")
      let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
      let token = tokenParts.joined()
      logger.info("Device Token: \(token)")
      QYSDK.shared().updateApnsToken(deviceToken)
      ViewModel.shared.deviceToken = token
   }

   func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      logger.info("Failed to register: \(error)")
   }

   func applicationDidEnterBackground(_ application: UIApplication) {
      let count = QYSDK.shared().conversationManager().allUnreadCount()
      application.applicationIconBadgeNumber = count
   }

   func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      logger.info("Received remote notification.\(userInfo)")
   }

   func getNotificationSettings() {
      UNUserNotificationCenter.current().getNotificationSettings { settings in
         logger.info("Notification settings: \(settings)")
         guard settings.authorizationStatus == .authorized else { return }
         DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
         }
      }
   }

   func registerForPushNotifications() {
      UNUserNotificationCenter.current()
         .requestAuthorization(
            options: [.alert, .sound, .badge]) { [weak self] granted, _ in
               logger.info("Permission granted: \(granted)")
               guard granted else { return }
               self?.getNotificationSettings()
         }
   }
    
    
    
}

@main
struct JiaoZiTaxiApp: App {
   @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
   @ObservedObject var locationManager = LocationManager.shared
   @ObservedObject var vm = ViewModel.shared
   @StateObject var db = DataManager.shared

   init() {
      logger.info("app start initing.....")
   }

   var body: some Scene {
      WindowGroup {
         ContentView(
            store: Store(
               initialState: AppState(),
               reducer: counterReducer,
               environment: AppEnvironment()))
            .environmentObject(locationManager)
            .environmentObject(vm)
            .environment(\.locale, .init(identifier: vm.language.rawValue))
            .environment(\.managedObjectContext, db.persistentContainer.viewContext)
            .task {
               let languages = Localize.availableLanguages()
               print("Support languages: \(languages)")

               print("device-id:\(String(describing: PhoneDevice().deviceId))")
               let currentLanguage = Localize.currentLanguage()
               print("Current language: \(currentLanguage)")
               print("当前位置".localized())

            }
            
      }
   }
}
